package com.LeeCode;

/**
 * 行相等的最少多米诺旋转
 */

public class Code1007 {
    public static void main(String[] args) {
        int[] tops = {2, 1, 2, 4, 2, 2};
        int[] bottoms = {5, 2, 6, 2, 3, 2};
        System.out.println(new Code1007().minDominoRotations(tops, bottoms));
    }

    public int minDominoRotations(int[] tops, int[] bottoms) {
        int top = check(tops, bottoms, tops[0]);
        int bottom = check(tops, bottoms, bottoms[0]);

        if (top == -1 && bottom == -1) {
            return -1;
        } else if (top == -1) {
            return bottom;
        } else if (bottom == -1) {
            return top;
        } else {
            return Math.min(top, bottom);
        }
    }

    private int check(int[] tops, int[] bottoms, int candidate) {
        int swapsTop = 0; // swaps to make tops all candidate
        int swapsBottom = 0; // swaps to make bottoms all candidate
        for (int i = 0; i < tops.length; i++) {
            if (tops[i] != candidate && bottoms[i] != candidate) {
                return -1;
            }
            if (tops[i] != candidate) {
                swapsTop++;
            }
            if (bottoms[i] != candidate) {
                swapsBottom++;
            }
        }
        return Math.min(swapsTop, swapsBottom);
    }
}
